<template>
  <div class="archives-page">
    <h1 class="page-title">文章归档</h1>

    <div class="timeline-container">
      <el-timeline>
        <el-timeline-item
          v-for="(timeGroup, index) in timelineGroups"
          :key="index"
          :timestamp="timeGroup.month"
          placement="top"
        >
          <el-card class="timeline-card">
            <div
              v-for="post in timeGroup.posts"
              :key="post.id"
              class="timeline-post"
            >
              <div class="post-date">{{ formatDate(post.date) }}</div>
              <div class="post-title">{{ post.title }}</div>
            </div>
          </el-card>
        </el-timeline-item>
      </el-timeline>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { useBlogStore } from '../store/blogStore'
import type { Post } from '../store/blogStore'

const blogStore = useBlogStore()

// 按月份分组文章
const timelineGroups = computed(() => {
  const groups: Record<string, { month: string; posts: Post[] }> = {}

  blogStore.posts.forEach(post => {
    const date = new Date(post.date)
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const key = `${year}-${month}`
    const displayMonth = `${year}年${month}月`

    if (!groups[key]) {
      groups[key] = {
        month: displayMonth,
        posts: []
      }
    }

    groups[key].posts.push(post)
  })

  // 将分组转换为数组并按日期排序
  return Object.values(groups).sort((a, b) => {
    const [yearA, monthA] = a.month.split('年')[0].split('月')[0].split('-').map(Number)
    const [yearB, monthB] = b.month.split('年')[0].split('月')[0].split('-').map(Number)

    if (yearA !== yearB) {
      return yearB - yearA // 年份降序
    }

    return monthB - monthA // 月份降序
  })
})

// 格式化日期为 "DD日" 格式
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return `${date.getDate()}日`
}
</script>

<style scoped>
.archives-page {
  width: 100%;
  padding: 20px 0;
}

.page-title {
  margin: 0 0 30px;
  font-size: 28px;
  font-weight: 600;
  text-align: center;
}

.timeline-container {
  max-width: 800px;
  margin: 0 auto;
}

.timeline-card {
  margin-bottom: 10px;
}

.timeline-post {
  display: flex;
  padding: 10px 0;
  border-bottom: 1px dashed var(--border-color);
}

.timeline-post:last-child {
  border-bottom: none;
}

.post-date {
  min-width: 40px;
  color: #999;
  margin-right: 20px;
}

.post-title {
  flex: 1;
  font-weight: 500;
}

.post-title:hover {
  color: var(--accent-color);
  cursor: pointer;
}
</style>
